package controllers

import (
	"blog/app/common"
	"blog/app/entity"
	"blog/app/server"
	"blog/app/utils"
	"github.com/kataras/iris"
	"github.com/syssam/go-validator"
	"log"
	"strings"
)

type ArticleController struct {
}

var articleServer server.ArticleServer
var validate = validator.New()

func (*ArticleController) QueryHandler(ctx iris.Context) {
	log.Println("article controller")
	pageNum := utils.Int2Uint(ctx.URLParamIntDefault("pageNum", 1))
	tagId := utils.Int2Uint(ctx.URLParamIntDefault("tagId", 0))
	createDate := ctx.URLParamDefault("createDate", "")
	title := ctx.URLParamDefault("title", "")

	page := common.NewPage(pageNum)
	params := &entity.QueryParam{
		TagId:      uint64(tagId),
		CreateDate: createDate,
		Title:      title,
	}
	articles := articleServer.Query(page, params)
	if articles == nil {
		ctx.JSON(common.NewCoder(common.NODATE, nil))
		return
	}
	ctx.JSON(common.NewCoderDefault(struct {
		Page common.Page `json:"page"`
		List interface{} `json:"list"`
	}{
		Page: *page,
		List: articles,
	}))
}


func (*ArticleController) GetHandler(ctx iris.Context){
	id := ctx.Params().GetUint64Default("id",0)
	ip := ctx.Request().RemoteAddr
	if ip != ""{
		ip = ip[:strings.LastIndex(ip,":")]
	}
	a := articleServer.Get(id,ip)
	ctx.JSON(common.NewCoderDefault(a))
}

// 管理
func (*ArticleController) GetAdminHandler(ctx iris.Context){
	id := ctx.Params().GetUint64Default("id",0)
	a := articleServer.Get(id,"")
	ctx.JSON(common.NewCoderDefault(a))
}

func (*ArticleController) GetCreatedateStatHandler(ctx iris.Context){
	ads := articleServer.GetCreatedateStat()
	ctx.JSON(common.NewCoderDefault(ads))
}


func (*ArticleController) InsertHandler(ctx iris.Context){
	param := &entity.ArticleParam{}
	ctx.ReadJSON(param)
	if err := validator.ValidateStruct(param); err != nil {
		ctx.JSON(common.NewCoderBool(false))
		return
	}
	ok := articleServer.Insert(param)
	ctx.JSON(common.NewCoderBool(ok))
}

func (*ArticleController) UpdateHandler(ctx iris.Context){
	id := ctx.Params().GetUint64Default("id",0)
	param := &entity.ArticleParam{}
	ctx.ReadJSON(&param)
	articleServer.Update(id,param)
	ctx.JSON(common.NewCoderDefault(nil))
}

func (*ArticleController) DeleteHandler(ctx iris.Context){
	id := ctx.Params().GetUint64Default("id",0)
	ok := articleServer.Delete(id)
	ctx.JSON(common.NewCoderBool(ok))
}